/*
 * @Author: MiNine
 * @Date: 2020-09-19 09:29:20
 * @LastEditors: MiNine
 * @LastEditTime: 2020-09-27 16:41:59
 * @Description: 保险订单
 */
const {
    InsureOrder
} = require('../models/insureOrderModel');
const {
    Client
} = require('../models/clientModel');
const {
    InsureProduct
} = require('../models/insureProductModel');
const {
    Admin
} = require('../models/adminModel')
const dayjs = require('dayjs');

/**
 * 增加 保险订单
 * @param {*} req 
 * @param {*} res 
 */
async function addOrder(req, res) {
    const {
        clientId,
        insureProductId,
    } = req.body;

    try {
        //获得客户
        const client = await Client.findById(clientId);
        //获得客户的对于销售员ID
        const adminId = client.belongAdminId;
        //获得当前保险产品数据
        const {
            productName,
            productPrice,
            compensation,
        } = await InsureProduct.findById(insureProductId);

        const newInsureOrder = await InsureOrder.create({
            clientId,
            adminId,
            productName,
            payPrice: productPrice,
            compensation,
            dueTime: dayjs().add(18, 'day').format('YYYY-MM-DD'),
            inForceTime: dayjs().add(3, 'day').format('YYYY-MM-DD'),
            status: 3,
        });

        if (newInsureOrder) {
            //添加生成订单ID进入用户集合
            await Client.findByIdAndUpdate(client, {
                $push: {
                    insureOrdList: newInsureOrder._id
                }
            });

            //添加生成订单ID进入销售员集合
            await Admin.findByIdAndUpdate(adminId, {
                $push: {
                    insureOrdList: newInsureOrder._id
                }
            });

            res.send({
                status: 1,
                msg: "addInsureOrder successful"
            })
        } else {
            res.send({
                status: 0,
                msg: "addInsureOrder fail"
            })
        }
    } catch (error) {
        console.log("addOrder ERROR:" + error);
        res.send({
            status: 0,
            msg: error
        })
    }


}

/**
 * 删除 保险订单
 * @param {*} req 
 * @param {*} res 
 */
async function delOrder(req, res) {
    const {
        _id
    } = req.body;

    try {
        const delInsureOrder = await InsureOrder.findByIdAndDelete(_id);
        if (delInsureOrder) {
            //删除对于客户的订单
            await Client.updateOne({
                _id: delInsureOrder.clientId
            }, {
                $pull: {
                    insureOrdList: delInsureOrder._id
                }
            });
            //删除对于操作员的订单
            await Admin.updateOne({
                _id: delInsureOrder.adminId
            }, {
                $pull: {
                    insureOrdList: delInsureOrder._id
                }
            });

            res.send({
                status: 1,
                data: delInsureOrder,
                msg: "delInsureOrder successful"
            })
        } else {
            res.send({
                status: 0,
                msg: "delInsureOrder fail , no target"
            })
        }
    } catch (error) {
        console.log("delOrder ERROR:" + error);
        res.send({
            status: 0,
            msg: error
        })
    }

}

/**
 * 处理 订单退保申请
 * @param {*} req 
 * @param {*} res 
 */
async function modOrderStatus(req, res) {
    const {
        _id,
        status
    } = req.body;


    try {
        const updateInsureOrder = await InsureOrder.findByIdAndUpdate(_id, {
            status
        }, {
            new: true
        });
        if (updateInsureOrder) {
            res.send({
                status: 1,
                msg: "updateInsureOrder successful"
            })
        } else {
            res.send({
                status: 0,
                msg: "updateInsureOrder fail , no target"
            })
        }
    } catch (error) {
        console.log("modOrderStatus ERROR:" + error);
        res.send({
            status: 0,
            msg: error
        })
    }

}

/**
 * 修改 订单信息
 * @param {*} req 
 * @param {*} res 
 */
async function modOrder(req, res) {
    const {
        _id,
        updateDate
    } = req.body;

    try {
        const updateInsureOrder = await InsureOrder.findByIdAndUpdate(_id, updateDate, {
            new: true
        });

        if (updateInsureOrder) {
            res.send({
                status: 1,
                msg: "updateInsureOrder successful"
            })
        } else {
            res.send({
                status: 0,
                msg: "updateInsureOrder fail , no target"
            })
        }
    } catch (error) {
        console.log("modOrder ERROR:" + error);
        res.send({
            status: 0,
            msg: error
        })
    }
}

/**
 * 按 adminID 获取订单
 * @param {*} req 
 * @param {*} res 
 */
async function getOrders(req, res) {
    let {
        adminId,
        pageSize,
        currentPage
    } = req.query;

    pageSize -= 0;
    currentPage -= 0;

    try {
        let findAdmin = await Admin
            .findById(adminId)
            .populate({
                path: 'insureOrdList',
                populate: [{
                    path: 'clientId',
                    select: "nickName"
                }],
            })

        if (['1', '9'].some(item => item == findAdmin.permission)) {
            const ALLInsureOrders = await InsureOrder
                .find()
                .populate({
                    path: 'clientId',
                    select: "nickName"
                });
            findAdmin.insureOrdList = ALLInsureOrders;
        }

        let total = findAdmin.insureOrdList.length;
        let totalPages = Math.ceil(total / pageSize);

        if (findAdmin) {
            res.send({
                status: 1,
                data: {
                    total,
                    totalPages,
                    pageSize,
                    currentPage,
                    data: findAdmin.insureOrdList.slice((currentPage - 1) * pageSize, currentPage * pageSize)
                },
                msg: "findInsureOrder successful"
            })
        } else {
            res.send({
                status: 0,
                msg: "findInsureOrder fail , no target"
            })
        }
    } catch (error) {
        console.log("getOrders ERROR:" + error);
        res.send({
            status: 0,
            msg: error
        })
    }
}

/**
 * 按 订单ID 获取订单信息
 * @param {*} req 
 * @param {*} res 
 */
async function getOrder(req, res) {
    const {
        _id
    } = req.query;

    try {
        const findInsureOrder = await InsureOrder
            .findById(_id)
            .populate('adminId', 'nickName')
            .populate('clientId', 'nickName');

        if (findInsureOrder) {
            res.send({
                status: 1,
                data: findInsureOrder,
                msg: "findInsureOrder successful"
            })
        } else {
            res.send({
                status: 0,
                msg: "findInsureOrder fail , no target"
            })
        }
    } catch (error) {
        console.log("getOrders ERROR:" + error);
        res.send({
            status: 0,
            msg: error
        })
    }
}

module.exports = {
    addOrder,
    delOrder,
    modOrderStatus,
    modOrder,
    getOrders,
    getOrder
}